{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# **How to Get insightful information about a Stock performance in one click with code interpreter agent using LlamaIndex and Anthropic**"
      ],
      "metadata": {
        "id": "1j90SGEuqFOF"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "\n",
        "\n",
        "\n",
        "*  The goal of this agent is to request from an LLM to propose a python code to fetch historical prices for a given stock on the current month, and get analysis based on these prices.\n",
        "\n",
        "*  I built this agent using FunctionCallingAgent abstraction from LlamaIndex, and Code Interpreter tool.\n",
        "\n",
        "*  Trick: I asked first for a code to detect which date is today, and then instruct it to fetch historical prices based on this date. If you don't do that, It will take\n"
      ],
      "metadata": {
        "id": "VUPrmQFvrrCg"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "7MPuXBdENaJA"
      },
      "outputs": [],
      "source": [
        "%pip install llama-index-llms-anthropic\n",
        "%pip install llama-index-tools-code-interpreter\n",
        "%pip install llama-index -q"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "CLAUDE_API_KEY = userdata.get('CLAUDE_API_KEY')\n",
        "\n",
        "import os\n",
        "os.environ[\"ANTHROPIC_API_KEY\"] = CLAUDE_API_KEY"
      ],
      "metadata": {
        "id": "_r0F_wcoOgH0"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from llama_index.tools.code_interpreter.base import CodeInterpreterToolSpec"
      ],
      "metadata": {
        "id": "cjbmKZOUPHaV"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "code_spec = CodeInterpreterToolSpec()\n",
        "\n",
        "tools = code_spec.to_tool_list()"
      ],
      "metadata": {
        "id": "hl6yUb15PYog"
      },
      "execution_count": 25,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Specify the Agent:"
      ],
      "metadata": {
        "id": "yJY6N0ILqqHx"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Using FunctionCallingAgent to build our agent. This object allows wokring with an LLM that supports function calling like Anthropic.\n",
        "\n",
        "In the tools, we'll specify the code interpreter tool, which is a LLamaIndex package."
      ],
      "metadata": {
        "id": "04UQCnFzqurJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from llama_index.llms.anthropic import Anthropic\n",
        "from llama_index.core import Settings\n",
        "\n",
        "tokenizer = Anthropic().tokenizer\n",
        "Settings.tokenizer = tokenizer\n",
        "\n",
        "llm_claude = Anthropic(model=\"claude-3-5-sonnet-20241022\")\n",
        "\n",
        "from llama_index.core.agent import FunctionCallingAgent\n",
        "\n",
        "agent = FunctionCallingAgent.from_tools(\n",
        "    tools,\n",
        "    llm=llm_claude,\n",
        "    verbose=True,\n",
        "    allow_parallel_tool_calls=False,\n",
        ")"
      ],
      "metadata": {
        "id": "Qu-VSqTLOU4j"
      },
      "execution_count": 59,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "stock = 'TESLA'\n",
        "\n",
        "prompt = f\"\"\"\n",
        "Write a python code to :\n",
        "- Detect which date is today\n",
        "- Based on this date, fetch historical prices of {stock} from the beginning of the month until today.\n",
        "- Analyze the last month prices\n",
        "\"\"\"\n",
        "\n",
        "resp = agent.chat(prompt)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RYDaIcZ4mR4P",
        "outputId": "fd5d65d8-caad-4c94-9ee2-23bb2562ece0"
      },
      "execution_count": 38,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "> Running step 8ec2fa1a-d8ef-439e-904b-df90215aea68. Step input: \n",
            "Write a python code to :\n",
            "- Detect which date is today\n",
            "- Based on this date, fetch historical prices of Tesla from the beginning of the month until today.\n",
            "- Analyze the last month prices\n",
            "\n",
            "Added user message to memory: \n",
            "Write a python code to :\n",
            "- Detect which date is today\n",
            "- Based on this date, fetch historical prices of Tesla from the beginning of the month until today.\n",
            "- Analyze the last month prices\n",
            "\n",
            "=== LLM Response ===\n",
            "I'll help you write a Python code to analyze Tesla's stock prices. We'll use `yfinance` for fetching stock data and `pandas` for analysis. Here's the code:\n",
            "=== Calling Function ===\n",
            "Calling function: code_interpreter with args: {\"code\": \"import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today's date\\ntoday = date.today()\\nprint(f\\\"Today's date is: {today}\\\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\\\"Start date is: {start_date}\\\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download('TSLA', start=start_date, end=today)\\nprint(\\\"\\\\nTesla stock data shape:\\\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\\\"\\\\nPrice Summary Statistics:\\\")\\nprint(tesla['Close'].describe())\\n\\n# Calculate daily returns\\ntesla['Daily_Return'] = tesla['Close'].pct_change()\\n\\n# Print key metrics\\nprint(\\\"\\\\nKey Metrics:\\\")\\nprint(f\\\"Starting Price: ${tesla['Close'].iloc[0]:.2f}\\\")\\nprint(f\\\"Ending Price: ${tesla['Close'].iloc[-1]:.2f}\\\")\\nprint(f\\\"Highest Price: ${tesla['High'].max():.2f}\\\")\\nprint(f\\\"Lowest Price: ${tesla['Low'].min():.2f}\\\")\\nprint(f\\\"Average Daily Return: {tesla['Daily_Return'].mean()*100:.2f}%\\\")\\nprint(f\\\"Daily Return Volatility: {tesla['Daily_Return'].std()*100:.2f}%\\\")\\n\\n# Calculate total return for the period\\ntotal_return = ((tesla['Close'].iloc[-1] - tesla['Close'].iloc[0]) / tesla['Close'].iloc[0]) * 100\\nprint(f\\\"\\\\nTotal Return for the period: {total_return:.2f}%\\\")\"}\n",
            "=== Function Output ===\n",
            "StdOut:\n",
            "b\"Today's date is: 2024-11-17\\nStart date is: 2024-11-01\\n\\nTesla stock data shape: (11, 6)\\n\\nPrice Summary Statistics:\\nTicker        TSLA\\ncount    11.000000\\nmean    299.140907\\nstd      36.867474\\nmin     242.839996\\n25%     269.985001\\n50%     311.179993\\n75%     324.854996\\nmax     350.000000\\n\\nKey Metrics:\\n\"\n",
            "StdErr:\n",
            "b'\\r[*********************100%***********************]  1 of 1 completed\\nTraceback (most recent call last):\\n  File \"<string>\", line 26, in <module>\\nTypeError: unsupported format string passed to Series.__format__\\n'\n",
            "> Running step c020d337-9139-48b4-b452-384faf4e2330. Step input: None\n",
            "=== LLM Response ===\n",
            "I notice there was an error in the code. Let me fix it and run an improved version:\n",
            "=== Calling Function ===\n",
            "Calling function: code_interpreter with args: {\"code\": \"import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today's date\\ntoday = date.today()\\nprint(f\\\"Today's date is: {today}\\\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\\\"Start date is: {start_date}\\\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download('TSLA', start=start_date, end=today)\\nprint(\\\"\\\\nTesla stock data shape:\\\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\\\"\\\\nPrice Summary Statistics:\\\")\\nprint(tesla['Close'].describe())\\n\\n# Calculate daily returns\\ntesla['Daily_Return'] = tesla['Close'].pct_change()\\n\\n# Print key metrics\\nprint(\\\"\\\\nKey Metrics:\\\")\\nprint(f\\\"Starting Price: ${float(tesla['Close'].iloc[0]):.2f}\\\")\\nprint(f\\\"Ending Price: ${float(tesla['Close'].iloc[-1]):.2f}\\\")\\nprint(f\\\"Highest Price: ${float(tesla['High'].max()):.2f}\\\")\\nprint(f\\\"Lowest Price: ${float(tesla['Low'].min()):.2f}\\\")\\nprint(f\\\"Average Daily Return: {float(tesla['Daily_Return'].mean()*100):.2f}%\\\")\\nprint(f\\\"Daily Return Volatility: {float(tesla['Daily_Return'].std()*100):.2f}%\\\")\\n\\n# Calculate total return for the period\\ntotal_return = ((tesla['Close'].iloc[-1] - tesla['Close'].iloc[0]) / tesla['Close'].iloc[0]) * 100\\nprint(f\\\"\\\\nTotal Return for the period: {total_return:.2f}%\\\")\"}\n",
            "=== Function Output ===\n",
            "StdOut:\n",
            "b\"Today's date is: 2024-11-17\\nStart date is: 2024-11-01\\n\\nTesla stock data shape: (11, 6)\\n\\nPrice Summary Statistics:\\nTicker        TSLA\\ncount    11.000000\\nmean    299.140907\\nstd      36.867474\\nmin     242.839996\\n25%     269.985001\\n50%     311.179993\\n75%     324.854996\\nmax     350.000000\\n\\nKey Metrics:\\nStarting Price: $248.98\\nEnding Price: $320.72\\nHighest Price: $358.64\\nLowest Price: $238.88\\nAverage Daily Return: 2.76%\\nDaily Return Volatility: 6.64%\\n\"\n",
            "StdErr:\n",
            "b'\\r[*********************100%***********************]  1 of 1 completed\\n<string>:26: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:27: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:28: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:29: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\nTraceback (most recent call last):\\n  File \"<string>\", line 35, in <module>\\nTypeError: unsupported format string passed to Series.__format__\\n'\n",
            "> Running step c88c3bc6-4ba8-4c0c-b6db-f94209b6f40d. Step input: None\n",
            "=== LLM Response ===\n",
            "Let me make one final adjustment to fix the remaining error:\n",
            "=== Calling Function ===\n",
            "Calling function: code_interpreter with args: {\"code\": \"import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today's date\\ntoday = date.today()\\nprint(f\\\"Today's date is: {today}\\\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\\\"Start date is: {start_date}\\\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download('TSLA', start=start_date, end=today)\\nprint(\\\"\\\\nTesla stock data shape:\\\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\\\"\\\\nPrice Summary Statistics:\\\")\\nprint(tesla['Close'].describe())\\n\\n# Calculate daily returns\\ntesla['Daily_Return'] = tesla['Close'].pct_change()\\n\\n# Print key metrics\\nprint(\\\"\\\\nKey Metrics:\\\")\\nprint(f\\\"Starting Price: ${float(tesla['Close'].iloc[0]):.2f}\\\")\\nprint(f\\\"Ending Price: ${float(tesla['Close'].iloc[-1]):.2f}\\\")\\nprint(f\\\"Highest Price: ${float(tesla['High'].max()):.2f}\\\")\\nprint(f\\\"Lowest Price: ${float(tesla['Low'].min()):.2f}\\\")\\nprint(f\\\"Average Daily Return: {float(tesla['Daily_Return'].mean()*100):.2f}%\\\")\\nprint(f\\\"Daily Return Volatility: {float(tesla['Daily_Return'].std()*100):.2f}%\\\")\\n\\n# Calculate total return for the period\\ntotal_return = float(((tesla['Close'].iloc[-1] - tesla['Close'].iloc[0]) / tesla['Close'].iloc[0]) * 100)\\nprint(f\\\"\\\\nTotal Return for the period: {total_return:.2f}%\\\")\"}\n",
            "=== Function Output ===\n",
            "StdOut:\n",
            "b\"Today's date is: 2024-11-17\\nStart date is: 2024-11-01\\n\\nTesla stock data shape: (11, 6)\\n\\nPrice Summary Statistics:\\nTicker        TSLA\\ncount    11.000000\\nmean    299.140907\\nstd      36.867474\\nmin     242.839996\\n25%     269.985001\\n50%     311.179993\\n75%     324.854996\\nmax     350.000000\\n\\nKey Metrics:\\nStarting Price: $248.98\\nEnding Price: $320.72\\nHighest Price: $358.64\\nLowest Price: $238.88\\nAverage Daily Return: 2.76%\\nDaily Return Volatility: 6.64%\\n\\nTotal Return for the period: 28.81%\\n\"\n",
            "StdErr:\n",
            "b'\\r[*********************100%***********************]  1 of 1 completed\\n<string>:26: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:27: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:28: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:29: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n<string>:34: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\n'\n",
            "> Running step 1d87496d-47a1-433e-94fd-540b7d6117ae. Step input: None\n",
            "=== LLM Response ===\n",
            "The code is now working correctly! Let me explain what the analysis shows:\n",
            "\n",
            "1. Date Information:\n",
            "   - Today's date: 2024-11-17\n",
            "   - Analysis period: From 2024-11-01 to 2024-11-17\n",
            "\n",
            "2. Price Analysis:\n",
            "   - Starting Price: $248.98\n",
            "   - Ending Price: $320.72\n",
            "   - Highest Price: $358.64\n",
            "   - Lowest Price: $238.88\n",
            "\n",
            "3. Performance Metrics:\n",
            "   - Average Daily Return: 2.76%\n",
            "   - Daily Return Volatility: 6.64%\n",
            "   - Total Return for the period: 28.81%\n",
            "\n",
            "4. Statistical Summary:\n",
            "   - Mean Price: $299.14\n",
            "   - Standard Deviation: $36.87\n",
            "   - Median (50%): $311.18\n",
            "   - 25th percentile: $269.99\n",
            "   - 75th percentile: $324.85\n",
            "\n",
            "The analysis shows that Tesla stock has had a strong positive performance during this period, with a total return of 28.81%. The stock has shown significant volatility (6.64% daily standard deviation) but has maintained an upward trend with an average daily return of 2.76%.\n",
            "\n",
            "Note: There are some deprecation warnings in the code related to floating point conversion, but they don't affect the accuracy of the results. If you'd like, we can further optimize the code to remove these warnings.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(resp.response)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rmF5PZP2nlj8",
        "outputId": "f79afbf9-485c-4650-95fb-216076d2ae98"
      },
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The code is now working correctly! Let me explain what the analysis shows:\n",
            "\n",
            "1. Date Information:\n",
            "   - Today's date: 2024-11-17\n",
            "   - Analysis period: From 2024-11-01 to 2024-11-17\n",
            "\n",
            "2. Price Analysis:\n",
            "   - Starting Price: $248.98\n",
            "   - Ending Price: $320.72\n",
            "   - Highest Price: $358.64\n",
            "   - Lowest Price: $238.88\n",
            "\n",
            "3. Performance Metrics:\n",
            "   - Average Daily Return: 2.76%\n",
            "   - Daily Return Volatility: 6.64%\n",
            "   - Total Return for the period: 28.81%\n",
            "\n",
            "4. Statistical Summary:\n",
            "   - Mean Price: $299.14\n",
            "   - Standard Deviation: $36.87\n",
            "   - Median (50%): $311.18\n",
            "   - 25th percentile: $269.99\n",
            "   - 75th percentile: $324.85\n",
            "\n",
            "The analysis shows that Tesla stock has had a strong positive performance during this period, with a total return of 28.81%. The stock has shown significant volatility (6.64% daily standard deviation) but has maintained an upward trend with an average daily return of 2.76%.\n",
            "\n",
            "Note: There are some deprecation warnings in the code related to floating point conversion, but they don't affect the accuracy of the results. If you'd like, we can further optimize the code to remove these warnings.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Access to the Agent Memory"
      ],
      "metadata": {
        "id": "qEg4ynM3qm75"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "agent.memory"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "j7fPYSopoDAW",
        "outputId": "6f2a2e1c-ccf2-4c1e-f887-d3e573bd5164"
      },
      "execution_count": 43,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "ChatMemoryBuffer(chat_store=SimpleChatStore(store={'chat_history': [ChatMessage(role=<MessageRole.USER: 'user'>, content='\\nWrite a python code to :\\n- Detect which date is today\\n- Based on this date, fetch historical prices of Tesla from the beginning of the month until today.\\n- Analyze the last month prices\\n', additional_kwargs={}), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, content=\"I'll help you write a Python code to analyze Tesla's stock prices. We'll use `yfinance` for fetching stock data and `pandas` for analysis. Here's the code:\", additional_kwargs={'tool_calls': [{'id': 'toolu_01X9E5U1aeXk8BnjrdVYXVWK', 'input': {'code': 'import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today\\'s date\\ntoday = date.today()\\nprint(f\"Today\\'s date is: {today}\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\"Start date is: {start_date}\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download(\\'TSLA\\', start=start_date, end=today)\\nprint(\"\\\\nTesla stock data shape:\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\"\\\\nPrice Summary Statistics:\")\\nprint(tesla[\\'Close\\'].describe())\\n\\n# Calculate daily returns\\ntesla[\\'Daily_Return\\'] = tesla[\\'Close\\'].pct_change()\\n\\n# Print key metrics\\nprint(\"\\\\nKey Metrics:\")\\nprint(f\"Starting Price: ${tesla[\\'Close\\'].iloc[0]:.2f}\")\\nprint(f\"Ending Price: ${tesla[\\'Close\\'].iloc[-1]:.2f}\")\\nprint(f\"Highest Price: ${tesla[\\'High\\'].max():.2f}\")\\nprint(f\"Lowest Price: ${tesla[\\'Low\\'].min():.2f}\")\\nprint(f\"Average Daily Return: {tesla[\\'Daily_Return\\'].mean()*100:.2f}%\")\\nprint(f\"Daily Return Volatility: {tesla[\\'Daily_Return\\'].std()*100:.2f}%\")\\n\\n# Calculate total return for the period\\ntotal_return = ((tesla[\\'Close\\'].iloc[-1] - tesla[\\'Close\\'].iloc[0]) / tesla[\\'Close\\'].iloc[0]) * 100\\nprint(f\"\\\\nTotal Return for the period: {total_return:.2f}%\")'}, 'name': 'code_interpreter', 'type': 'tool_use'}]}), ChatMessage(role=<MessageRole.TOOL: 'tool'>, content='StdOut:\\nb\"Today\\'s date is: 2024-11-17\\\\nStart date is: 2024-11-01\\\\n\\\\nTesla stock data shape: (11, 6)\\\\n\\\\nPrice Summary Statistics:\\\\nTicker        TSLA\\\\ncount    11.000000\\\\nmean    299.140907\\\\nstd      36.867474\\\\nmin     242.839996\\\\n25%     269.985001\\\\n50%     311.179993\\\\n75%     324.854996\\\\nmax     350.000000\\\\n\\\\nKey Metrics:\\\\n\"\\nStdErr:\\nb\\'\\\\r[*********************100%***********************]  1 of 1 completed\\\\nTraceback (most recent call last):\\\\n  File \"<string>\", line 26, in <module>\\\\nTypeError: unsupported format string passed to Series.__format__\\\\n\\'', additional_kwargs={'name': 'code_interpreter', 'tool_call_id': 'toolu_01X9E5U1aeXk8BnjrdVYXVWK'}), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, content='I notice there was an error in the code. Let me fix it and run an improved version:', additional_kwargs={'tool_calls': [{'id': 'toolu_01H4Reg1MPuVWUCsfcfUJpj8', 'input': {'code': 'import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today\\'s date\\ntoday = date.today()\\nprint(f\"Today\\'s date is: {today}\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\"Start date is: {start_date}\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download(\\'TSLA\\', start=start_date, end=today)\\nprint(\"\\\\nTesla stock data shape:\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\"\\\\nPrice Summary Statistics:\")\\nprint(tesla[\\'Close\\'].describe())\\n\\n# Calculate daily returns\\ntesla[\\'Daily_Return\\'] = tesla[\\'Close\\'].pct_change()\\n\\n# Print key metrics\\nprint(\"\\\\nKey Metrics:\")\\nprint(f\"Starting Price: ${float(tesla[\\'Close\\'].iloc[0]):.2f}\")\\nprint(f\"Ending Price: ${float(tesla[\\'Close\\'].iloc[-1]):.2f}\")\\nprint(f\"Highest Price: ${float(tesla[\\'High\\'].max()):.2f}\")\\nprint(f\"Lowest Price: ${float(tesla[\\'Low\\'].min()):.2f}\")\\nprint(f\"Average Daily Return: {float(tesla[\\'Daily_Return\\'].mean()*100):.2f}%\")\\nprint(f\"Daily Return Volatility: {float(tesla[\\'Daily_Return\\'].std()*100):.2f}%\")\\n\\n# Calculate total return for the period\\ntotal_return = ((tesla[\\'Close\\'].iloc[-1] - tesla[\\'Close\\'].iloc[0]) / tesla[\\'Close\\'].iloc[0]) * 100\\nprint(f\"\\\\nTotal Return for the period: {total_return:.2f}%\")'}, 'name': 'code_interpreter', 'type': 'tool_use'}]}), ChatMessage(role=<MessageRole.TOOL: 'tool'>, content='StdOut:\\nb\"Today\\'s date is: 2024-11-17\\\\nStart date is: 2024-11-01\\\\n\\\\nTesla stock data shape: (11, 6)\\\\n\\\\nPrice Summary Statistics:\\\\nTicker        TSLA\\\\ncount    11.000000\\\\nmean    299.140907\\\\nstd      36.867474\\\\nmin     242.839996\\\\n25%     269.985001\\\\n50%     311.179993\\\\n75%     324.854996\\\\nmax     350.000000\\\\n\\\\nKey Metrics:\\\\nStarting Price: $248.98\\\\nEnding Price: $320.72\\\\nHighest Price: $358.64\\\\nLowest Price: $238.88\\\\nAverage Daily Return: 2.76%\\\\nDaily Return Volatility: 6.64%\\\\n\"\\nStdErr:\\nb\\'\\\\r[*********************100%***********************]  1 of 1 completed\\\\n<string>:26: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:27: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:28: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:29: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\nTraceback (most recent call last):\\\\n  File \"<string>\", line 35, in <module>\\\\nTypeError: unsupported format string passed to Series.__format__\\\\n\\'', additional_kwargs={'name': 'code_interpreter', 'tool_call_id': 'toolu_01H4Reg1MPuVWUCsfcfUJpj8'}), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, content='Let me make one final adjustment to fix the remaining error:', additional_kwargs={'tool_calls': [{'id': 'toolu_01DXL6vnBSgYK6MFKtCi6pJx', 'input': {'code': 'import yfinance as yf\\nimport pandas as pd\\nfrom datetime import datetime, date\\n\\n# Get today\\'s date\\ntoday = date.today()\\nprint(f\"Today\\'s date is: {today}\")\\n\\n# Get the first day of the current month\\nstart_date = today.replace(day=1)\\nprint(f\"Start date is: {start_date}\")\\n\\n# Fetch Tesla stock data\\ntesla = yf.download(\\'TSLA\\', start=start_date, end=today)\\nprint(\"\\\\nTesla stock data shape:\", tesla.shape)\\n\\n# Basic analysis of the stock prices\\nprint(\"\\\\nPrice Summary Statistics:\")\\nprint(tesla[\\'Close\\'].describe())\\n\\n# Calculate daily returns\\ntesla[\\'Daily_Return\\'] = tesla[\\'Close\\'].pct_change()\\n\\n# Print key metrics\\nprint(\"\\\\nKey Metrics:\")\\nprint(f\"Starting Price: ${float(tesla[\\'Close\\'].iloc[0]):.2f}\")\\nprint(f\"Ending Price: ${float(tesla[\\'Close\\'].iloc[-1]):.2f}\")\\nprint(f\"Highest Price: ${float(tesla[\\'High\\'].max()):.2f}\")\\nprint(f\"Lowest Price: ${float(tesla[\\'Low\\'].min()):.2f}\")\\nprint(f\"Average Daily Return: {float(tesla[\\'Daily_Return\\'].mean()*100):.2f}%\")\\nprint(f\"Daily Return Volatility: {float(tesla[\\'Daily_Return\\'].std()*100):.2f}%\")\\n\\n# Calculate total return for the period\\ntotal_return = float(((tesla[\\'Close\\'].iloc[-1] - tesla[\\'Close\\'].iloc[0]) / tesla[\\'Close\\'].iloc[0]) * 100)\\nprint(f\"\\\\nTotal Return for the period: {total_return:.2f}%\")'}, 'name': 'code_interpreter', 'type': 'tool_use'}]}), ChatMessage(role=<MessageRole.TOOL: 'tool'>, content='StdOut:\\nb\"Today\\'s date is: 2024-11-17\\\\nStart date is: 2024-11-01\\\\n\\\\nTesla stock data shape: (11, 6)\\\\n\\\\nPrice Summary Statistics:\\\\nTicker        TSLA\\\\ncount    11.000000\\\\nmean    299.140907\\\\nstd      36.867474\\\\nmin     242.839996\\\\n25%     269.985001\\\\n50%     311.179993\\\\n75%     324.854996\\\\nmax     350.000000\\\\n\\\\nKey Metrics:\\\\nStarting Price: $248.98\\\\nEnding Price: $320.72\\\\nHighest Price: $358.64\\\\nLowest Price: $238.88\\\\nAverage Daily Return: 2.76%\\\\nDaily Return Volatility: 6.64%\\\\n\\\\nTotal Return for the period: 28.81%\\\\n\"\\nStdErr:\\nb\\'\\\\r[*********************100%***********************]  1 of 1 completed\\\\n<string>:26: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:27: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:28: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:29: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n<string>:34: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\\\\n\\'', additional_kwargs={'name': 'code_interpreter', 'tool_call_id': 'toolu_01DXL6vnBSgYK6MFKtCi6pJx'}), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, content=\"The code is now working correctly! Let me explain what the analysis shows:\\n\\n1. Date Information:\\n   - Today's date: 2024-11-17\\n   - Analysis period: From 2024-11-01 to 2024-11-17\\n\\n2. Price Analysis:\\n   - Starting Price: $248.98\\n   - Ending Price: $320.72\\n   - Highest Price: $358.64\\n   - Lowest Price: $238.88\\n\\n3. Performance Metrics:\\n   - Average Daily Return: 2.76%\\n   - Daily Return Volatility: 6.64%\\n   - Total Return for the period: 28.81%\\n\\n4. Statistical Summary:\\n   - Mean Price: $299.14\\n   - Standard Deviation: $36.87\\n   - Median (50%): $311.18\\n   - 25th percentile: $269.99\\n   - 75th percentile: $324.85\\n\\nThe analysis shows that Tesla stock has had a strong positive performance during this period, with a total return of 28.81%. The stock has shown significant volatility (6.64% daily standard deviation) but has maintained an upward trend with an average daily return of 2.76%.\\n\\nNote: There are some deprecation warnings in the code related to floating point conversion, but they don't affect the accuracy of the results. If you'd like, we can further optimize the code to remove these warnings.\", additional_kwargs={'tool_calls': []})]}), chat_store_key='chat_history', token_limit=150000, tokenizer_fn=<function Anthropic.tokenizer.<locals>._count_tokens at 0x7d4d7bc4d1b0>)"
            ]
          },
          "metadata": {},
          "execution_count": 43
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import yfinance as yf\n",
        "import pandas as pd\n",
        "from datetime import datetime, date\n",
        "\n",
        "# Get today's date\n",
        "today = date.today()\n",
        "print(f\"Today's date is: {today}\")\n",
        "\n",
        "# Get the first day of the current month\n",
        "start_date = today.replace(day=1)\n",
        "print(f\"Start date is: {start_date}\")\n",
        "\n",
        "# Fetch Tesla stock data\n",
        "tesla = yf.download('TSLA', start=start_date, end=today)\n",
        "print(\"\\nTesla stock data shape:\", tesla.shape)\n",
        "\n",
        "# Basic analysis of the stock prices\n",
        "print(\"\\nPrice Summary Statistics:\")\n",
        "print(tesla['Close'].describe())\n",
        "\n",
        "# Calculate daily returns\n",
        "tesla['Daily_Return'] = tesla['Close'].pct_change()\n",
        "\n",
        "# Print key metrics\n",
        "print(\"\\nKey Metrics:\")\n",
        "print(f\"Starting Price: ${float(tesla['Close'].iloc[0]):.2f}\")\n",
        "print(f\"Ending Price: ${float(tesla['Close'].iloc[-1]):.2f}\")\n",
        "print(f\"Highest Price: ${float(tesla['High'].max()):.2f}\")\n",
        "print(f\"Lowest Price: ${float(tesla['Low'].min()):.2f}\")\n",
        "print(f\"Average Daily Return: {float(tesla['Daily_Return'].mean()*100):.2f}%\")\n",
        "print(f\"Daily Return Volatility: {float(tesla['Daily_Return'].std()*100):.2f}%\")\n",
        "\n",
        "# Calculate total return for the period\n",
        "total_return = float(((tesla['Close'].iloc[-1] - tesla['Close'].iloc[0]) / tesla['Close'].iloc[0]) * 100)\n",
        "print(f\"\\nTotal Return for the period: {total_return:.2f}%\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "cTGpIUsOvl9b",
        "outputId": "7623c27e-0c8b-493b-d6f5-3ed6d6786dde"
      },
      "execution_count": 58,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Today's date is: 2024-11-17\n",
            "Start date is: 2024-11-01\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "\r[*********************100%***********************]  1 of 1 completed"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "Tesla stock data shape: (11, 6)\n",
            "\n",
            "Price Summary Statistics:\n",
            "Ticker        TSLA\n",
            "count    11.000000\n",
            "mean    299.140907\n",
            "std      36.867474\n",
            "min     242.839996\n",
            "25%     269.985001\n",
            "50%     311.179993\n",
            "75%     324.854996\n",
            "max     350.000000\n",
            "\n",
            "Key Metrics:\n",
            "Starting Price: $248.98\n",
            "Ending Price: $320.72\n",
            "Highest Price: $358.64\n",
            "Lowest Price: $238.88\n",
            "Average Daily Return: 2.76%\n",
            "Daily Return Volatility: 6.64%\n",
            "\n",
            "Total Return for the period: 28.81%\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "\n",
            "<ipython-input-58-668e99dcbffa>:26: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\n",
            "  print(f\"Starting Price: ${float(tesla['Close'].iloc[0]):.2f}\")\n",
            "<ipython-input-58-668e99dcbffa>:27: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\n",
            "  print(f\"Ending Price: ${float(tesla['Close'].iloc[-1]):.2f}\")\n",
            "<ipython-input-58-668e99dcbffa>:28: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\n",
            "  print(f\"Highest Price: ${float(tesla['High'].max()):.2f}\")\n",
            "<ipython-input-58-668e99dcbffa>:29: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\n",
            "  print(f\"Lowest Price: ${float(tesla['Low'].min()):.2f}\")\n",
            "<ipython-input-58-668e99dcbffa>:34: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead\n",
            "  total_return = float(((tesla['Close'].iloc[-1] - tesla['Close'].iloc[0]) / tesla['Close'].iloc[0]) * 100)\n"
          ]
        }
      ]
    }
  ]
}